<?

$debug = 0;

$processBulkUpload = extractStringWithKeyFromArray("processBulkUpload", $_POST);

if($_SERVER['REQUEST_METHOD']=='POST' && $processBulkUpload){
//if(true) 
	$galleryUploadDir = CMS_SITE_DIR . "galleryUpload";
	$root = 0;
	
	include_once("cmsConfig.php");
	$cmsGalleryTreeFolderDocument = new CmsDocument($db);
	$cmsGalleryTreeFolderDocument->setFetchKeys(
			array(
				"documentcode" => "id",
				"title" => "name",
				"categorycode" => "parent",
				"author" => "isDir"
				
				)
		);	
	$cmsGalleryTreeFolderDocument->addDocumentType("docFileMod");
	$cmsGalleryTreeFolderDocument->addConstraint("author", 1);
	$cmsGalleryTreeFolderDocument->resetIterator();
	$galleryTree = array();
	while($row = $cmsGalleryTreeFolderDocument->nextDocument()){
		$row->parent = $row->parent ? $row->parent : 0;
		if(array_key_exists($row->parent, $galleryTree)){
			$galleryTree[$row->parent] = array_merge(
					$galleryTree[$row->parent],
					array( $row->name=>$row->id )
				);
		
		}else{
			$galleryTree[$row->parent] = array( $row->name=>$row->id );
			
		}
		
		if(!array_key_exists($row->id, $galleryTree))
			$galleryTree[$row->id] = array();
		
	}
	


	function readMultiFolder($path,$parent,$db){
		
		$authInfo = extractObjectWithKeyFromArray('authInfo', $_SESSION);
		
		$formId = extractNumberWithKeyFromArray("formid", $_GET);
		$documentTypeCode = "docFileMod";
		$fileElementId = 10104;//11362;
		
		global $galleryTree;
		$path .= "/";
		if ($dir_handle = @opendir($path)) {
			while (($file = readdir($dir_handle)) !== false) {
				
				if($file == "." || $file == "..")	continue;
				
				
				if(is_dir($path . $file)){

					if(array_key_exists($parent,$galleryTree) && array_key_exists($file,$galleryTree[$parent])){
						//echo "@exist directory: $file  <br />";
					}else{
						
						//echo "@new directory: $file  <br />";
						
						// cms writer - create folder
						$dataToSave = array();
						$dataToSave['documenttypecode'] = $documentTypeCode;
						$dataToSave['categorycode'] = $parent;
						$dataToSave['author'] = 1;
						$dataToSave['title'] = $file;
						
						$cmsWriter = new CmsWriter( $formId, null, &$dataToSave, &$authInfo, &$db);
						
						$res = $cmsWriter->processFormData();
						$documentCode = $cmsWriter->documentCode;
						if ( $res->hasErrors){
							if($debug){
								print '<span style="color:red">';
								myPrintR($res);
								print '</span>';
							}
														
						}
						
						
						$galleryTree[$parent][$file] = $documentCode;
					}
					
					
					readMultiFolder($path . $file, $galleryTree[$parent][$file], &$db);
					
				}else{
					//echo "filename: $file  <br />";

					//if(array_key_exists($parent,$galleryTree)){
					if(true){
						// cms writer - add image
						$dataToSave = array();
						$dataToSave['documenttypecode'] = $documentTypeCode;
						$dataToSave['categorycode'] = $parent;
						$filename =  explode('.',$file);
						if($filename[1] == "db")	@unlink($path . $file);
						$dataToSave['title'] = $filename[0];
						
							
						$cmsWriter = new CmsWriter( $formId, null, &$dataToSave, &$authInfo, &$db);
							
						$res = $cmsWriter->processFormData();
						$documentCode = $cmsWriter->documentCode;
						if ( $res->hasErrors){
							if($debug){
								print '<span style="color:red">';
								myPrintR($res);
								print '</span>';
							}
							
						
						}else{
							
							// get contents of a file into a string
							$handle = fopen($path . $file, "r");
							$contents = fread($handle, filesize($path . $file));
							fclose($handle);
							$mimetype = exec ('file -bi ' . escapeshellarg ( $path . $file ));
								
							$binarydata = new CmsTableWriter(CMS_BINARYDATA, $db);
							$fileId = $binarydata->db->getId('binarydatatablesequence');
							$binarydata->begin();
							$binarydata->addField( "content", $contents );
							$binarydata->addField( "filename", $file);
							$binarydata->addField( "mimetype", $mimetype);
							$binarydata->addField( "filesize", strlen($contents));
							$binarydata->addField( "filetypecode", 1);
							$binarydata->addField( "elementid", $fileElementId);
							$binarydata->addField( "documentcode", $documentCode );
							$binarydata->addField( "id", $fileId);
							$binarydata->newItem();	
							
							// 
							$contentdata = new CmsTableWriter('content', $db);
							$content = $contentdata->readItem($documentCode);
							
							$contentdata->begin();
							foreach($content as $k=>$v) {
								$contentdata->addField($k, $v);
							}				
							$contentdata->addField( "content", $fileId );
							$contentdata->saveItem();	
							
							//delete the file
							@unlink($path . $file);
							
						}
					}					
				}
			}
		}
	}
	
	
	
	
	if (is_dir($galleryUploadDir)) {
		
		readMultiFolder($galleryUploadDir, $root, &$db);
		if($debug)	myPrintR($galleryTree);
	}	

}

// categorycode  = parent
// author = folder?


?>
<form method="post">
<input type="submit" name="processBulkUpload" value="Bulk Upload" style="float:right" />
</form>
<br />
<br />
<table class="cms_browsetext" cellspacing="0" cellpadding="0" width="100%" border="0">
<?
$cmsDocument->setPageSize(null);
$cmsDocument->setPageNumber(null);
$cmsDocument->flush();
$cmsDocument->addDocumentType("docFileMod");

$parent = extractNumberWithKeyFromArray("parent", $_REQUEST);

if ($parent) {
	$cmsDocument->addConstraint("categorycode", $parent);
	echo "  <tr>\n";
	echo "    <td colspan='3'>\n";
	$isparent = true;
	$cmsDocument2 = new CmsDocument($db);
	$newparent = $parent;
	$path = "";
	
	while ($isparent) {
		$parentDoc = $cmsDocument2->openDocument($newparent);
		if ($parentDoc->categorycode) {
			$newparent = $parentDoc->categorycode;
		}
		else {
			$isparent = false;
		}
		if ($path) {
			$path = "<a href='/cms/html/index.php?fileNo=1&formid=".$parentDoc->formid."&parent=".$parentDoc->documentcode."'>".magicClean($parentDoc->title)."</a> / ".$path;
		}
		else {
			$path = "<a href='/cms/html/index.php?fileNo=1&formid=".$parentDoc->formid."&parent=".$parentDoc->documentcode."'>".magicClean($parentDoc->title)."</a>";
		}
	}
	
	$parentDoc = $cmsDocument2->openDocument($parent);
	echo "      Path: <a href='/cms/html/index.php?fileNo=1&formid=".$parentDoc->formid."'>Files Module</a> / ".$path."\n";
	echo "    </td>\n";
	echo "  </tr>\n";
	echo "  <tr>\n";
	echo "    <td colspan='3'>&nbsp;</td>\n";
	echo "  </tr>\n";
} else {
	$cmsDocument->addConstraint("categorycode", "<< NULL >>", "IS");
	$cmsDocument->addConstraint("categorycode", 0);
}

$cmsDocument->addConstraint('author',0,"=");
$cmsDocument->addSort("<<rank>>", "ASC");
$cmsDocument->addSort("documentcode", "ASC");
$cmsDocument->addSort("author", "DESC");
// $cmsDocument->setPageSize(100000);
$cmsDocument->resetIterator();
$count = 0;

while ($row = $cmsDocument->nextDocument()) {

?>
<tr align="center" valign="top">
<?

	for ($i=0; $i < 4; $i++){

		if ($i !=0)
			$row = $cmsDocument->nextDocument();
			
	$imageSrc = "/html/blob.php?attach=false&documentCode=".$row->documentcode."&scale=1&width=100";
	$viewUrl = $_SERVER["PHP_SELF"]."?fileNo=".FILES_AND_IMAGES_VIEW."&formid=".$row->formid."&parent=".$parent."&documentCode=".$row->documentcode;
	
?>
<td align="center" valign="top" class="cellBgWhite" width="25%">
<? if ($row) { ?>
<a href="<?= $viewUrl ?>" >
	<img width='100' src='<?= $imageSrc?>' alt='<?= $row->title ?>' border='0' class='mceImage' /><br />
</a>
<a href="<?= $viewUrl ?>"><?= ($row->title)?></a>
<?
$rankQuery = "SELECT documentcode, rank FROM cmscontentmetadata WHERE documentcode=" . $row->documentcode;
$db->executeQuery($rankQuery);
$rowRank = $db->nextRow();

$rowRankDisplay = null;
if($rowRank){
	$rowRankDisplay = $rowRank[1];
} 

if($rowRankDisplay){
	echo "<br />Rank: " . $rowRankDisplay;
} else {
	echo "<br />No Rank";
}
?>
<? } ?>
</td>
<?
	}
?>
</tr>
<?php
}
?>
</table>
<br />
<br />
<?php

	$cmsDocument->removeAllConstraintsForKey('author');

	$cmsDocument->addConstraint('author',0,"!=");
	
	$cmsDocument->resetIterator();
?>
<table class="cms_browsetext" cellspacing="0" cellpadding="0" width="100%" border="0">
<?
while ($row = $cmsDocument->nextDocument()) {	
	$browseUrl = $_SERVER['PHP_SELF'] . '?fileNo=1&formid='.$row->formid.'&parent=' . $row->documentcode;
?>
<tr>
<td width="28" align="center" valign="top" class="cellBg">
<a href="<?=$browseUrl ?>"><img src="/cms/images/iconFolder.gif" width="16" height="14" align="absmiddle" /></a>
</td>
<td width="622" valign="top" class="cellBg">
<a href="<?=$browseUrl ?>"><?= $row->title ?></a>
</td>
</tr>
<?
}
?>
</table>
<?
////

	//displayFolderQuickAdd($formDescription, $authInfo, null, null, $db );
	$addMode = CMS_ADD_FILES_AND_FOLDERS;
	$addLabel = "Create New Folder";
	
?>